package com.easyadmin.interceptor;

import com.alibaba.fastjson.JSON;
import com.easyadmin.annotation.GlobalInterceptor;
import com.easyadmin.entity.enums.ResponseCodeEnum;
import com.easyadmin.entity.vo.AjaxResponseVO;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


@Component
public class AppInterceptor implements HandlerInterceptor {
    private static final String CONTENT_TYPE = "Content-Type";
    private static final String CONTENT_TYPE_VALUE = "application/json;charset=UTF-8";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (null == handler) {
            return false;
        }
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        /**
         * 全局拦截，避免方法未设置拦截器，导致权限，日志等操作没有记录  如果不强制要求设置 GlobalInterceptor注解，可去掉次拦截器
         */
        HandlerMethod method = (HandlerMethod) handler;
        GlobalInterceptor interceptor = method.getMethodAnnotation(GlobalInterceptor.class);
        if (interceptor == null && request.getRequestURI().indexOf("checkCode") == -1) {
            response.setHeader(CONTENT_TYPE, CONTENT_TYPE_VALUE);
            response.setStatus(HttpStatus.OK.value());
            PrintWriter writer = response.getWriter();
            AjaxResponseVO ajaxResponse = new AjaxResponseVO<Object>();
            ajaxResponse.setCode(ResponseCodeEnum.CODE_405.getCode());
            ajaxResponse.setInfo(ResponseCodeEnum.CODE_405.getDesc());
            writer.print(JSON.toJSON(ajaxResponse));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}